import os
import sys
from tkinter import Tk, filedialog, Listbox, Button, messagebox
from logging import getLogger

from ..helper import export_to_excel, read_receipt
from .. import VERSION

logger = getLogger(__name__)


def resource_path(relative_path):
    """获取资源文件的绝对路径"""
    if hasattr(sys, "_MEIPASS"):
        # 打包后的环境
        base_path = sys._MEIPASS
    else:
        # 开发环境
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)


def add_files(listbox: Listbox):
    file_paths = filedialog.askopenfilenames(
        title="选择发票pdf", filetypes=[("PDF files", "*.pdf")]
    )
    if len(file_paths) == 0:
        return
    listbox.insert("end", *file_paths)
    logger.info(f"添加文件：{file_paths}")


def remove_selected_files(listbox: Listbox):
    selected_indices = listbox.curselection()
    for index in selected_indices:
        logger.info(f"移除文件：{listbox.get(index)}")
        listbox.delete(index)


def process_files(listbox: Listbox):
    file_paths = listbox.get(0, "end")
    if not file_paths:
        logger.warning("未选择文件")
        messagebox.showwarning("警告", "请选择文件")
        return

    excel_path = filedialog.asksaveasfilename(
        title="选择保存路径", filetypes=[("Excel files", "*.xlsx")]
    )
    if excel_path == "":
        logger.warning("未选择保存路径")
        return
    if not excel_path.endswith(".xlsx"):
        excel_path += ".xlsx"

    receipts = []
    for path in file_paths:
        _, receipt = read_receipt(path)
        receipts.append(receipt)

    try:
        logger.info(f"导出 Excel 到: {excel_path}")
        export_to_excel(excel_path, receipts)
        logger.info(f"发票信息已成功导出到 {excel_path}")
        messagebox.showinfo("成功", f"发票信息已成功导出到 {excel_path}")
    except Exception as e:
        logger.error(f"导出失败：{e}")
        messagebox.showerror("错误", f"导出失败：{e}")


def gui_run():
    root = Tk()
    root.title(f"发票信息提取工具 v{VERSION}")
    root.iconbitmap(resource_path(".") + "/icon.ico")
    root.geometry("500x300")
    root.resizable(False, False)

    listbox = Listbox(root, width=50, height=10)
    listbox.place(x=100, y=10, height=280, width=395)

    select_button = Button(
        root, text="添加文件", command=lambda: add_files(listbox), width=8
    )
    select_button.place(x=10, y=10, height=30, width=80)

    remove_button = Button(
        root,
        text="移除",
        command=lambda: remove_selected_files(listbox),
        width=8,
    )
    remove_button.place(x=10, y=50, height=30, width=80)

    process_button = Button(
        root, text="提取", command=lambda: process_files(listbox), width=8
    )
    process_button.place(x=10, y=260, height=30, width=80)

    root.mainloop()


if __name__ == "__main__":
    gui_run()
